<template>
  <div class="create-post-container">
    <el-form ref="postForm" :model="postForm" :rules="rules" label-position="right" label-width="100px" class="reply-form">
      <el-row :gutter="20">
        <el-col :span="18" :offset="3">
          <el-form-item label="标题" prop="title">
            <el-input v-model="postForm.title" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="18" :offset="3">
          <el-form-item label="描述" prop="content">
            <el-input v-model="postForm.content" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="18" :offset="3">
          <el-form-item label="链接" prop="url">
            <el-input v-model="postForm.url" />
            <div class="form-tips text-warning">以 http:// 或 https:// 开始</div>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="18" :offset="3">
          <el-form-item label="封面" prop="cover">
            <el-upload
              v-if="coverList < 1"
              :action="uploadUrl"
              :multiple="false"
              :limit="1"
              name="fies"
              :headers="{token}"
              :on-success="handleUploadSucc"
              :show-file-list="false"
              drag
              accept="image/jpeg,image/png,image/gif"
              class="drag-upload-wrapper"
            >
              <i class="el-icon-upload" />
              <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            </el-upload>

            <ul v-else class="thumb-img-list">
              <li
                v-for="(item, index) in coverList"
                :key="index"
                class="item"
              >
                <img :src="item.url" :alt="item.name" class="img">
                <div
                  class="el-icon-close close-btn"
                  title="点击可删除"
                  @click="handleUploadRemove(item)"
                />
              </li>
            </ul>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20">
        <el-col :span="9" :offset="3">
          <el-form-item label="图文类型" prop="type">
            <el-select
              v-model="postForm.type"
              placeholder="请选择"
              style="width:100%"
            >
              <el-option
                v-for="item in typeOptions"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="3" :offset="3">
          <el-form-item label="上线" prop="status">
            <el-switch v-model="postForm.status" :active-value="1" :inactive-value="0" />
          </el-form-item>
        </el-col>
      </el-row>

      <el-row :gutter="20" class="mt30">
        <el-col :span="18" :offset="3">
          <el-form-item>
            <el-button type="primary" @click="submitForm">提 交</el-button>
            <el-button @click="resetForm">重置</el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import {
  getReplyMessages,
  addReplyMessage,
  editReplyMessage
} from '@/api/replyMessage'
import { mapGetters } from 'vuex'

const defaultForm = {
  id: undefined,
  title: '',
  content: '',
  url: '',
  img: '',
  type: '',
  status: 0
}

export default {
  name: 'ReplyMessageForm',
  props: {
    isEdit: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      typeOptions: [
        {
          id: 1,
          name: '多图文'
        },
        {
          id: 2,
          name: '单图文'
        }
      ],
      coverList: [],
      postForm: Object.assign({}, defaultForm),
      loading: false,
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' },
          { min: 1, max: 50, message: '长度在 1 到 50 个字', trigger: 'blur' }
        ],
        type: [
          { required: true, message: '请选择类型', trigger: 'change' }
        ]
      },
      uploadUrl: process.env.VUE_APP_BASE_API + '/content/imgUpload'
    }
  },
  computed: {
    ...mapGetters([
      'token'
    ])
  },
  created() {
    if (this.isEdit) {
      const id = this.$route.params && this.$route.params.id
      this.fetchData(id)
    }
  },
  methods: {
    fetchData(id) {
      getReplyMessages({ id }).then(response => {
        const data = response.data[0]
        // console.log(data)
        this.coverList = []
        this.coverList.push({
          name: 'uploadCover' + 0,
          url: data.img
        })
        this.postForm.id = data.id
        this.postForm.title = data.title
        this.postForm.content = data.content
        this.postForm.url = data.url
        this.postForm.img = data.img
        this.postForm.type = data.type
        this.postForm.status = data.status
      }).catch(err => {
        console.log(err)
      })
    },
    handleUploadRemove(file) {
      const index = this.coverList.indexOf(file)
      if (index !== -1) {
        this.coverList.splice(index, 1)
        this.postForm.img = ''
      }
      // console.log(this.coverList)
    },
    handleUploadSucc(res) {
      // console.log(res)
      // this.postForm.cover = res.data

      res.data.forEach((item, index) => {
        if (this.coverList.indexOf(item) === -1) {
          this.postForm.img = item
          this.coverList.push({
            name: 'uploadCover' + index,
            url: item
          })
        }
      })
      console.log(this.postForm.img)
    },
    submitForm() {
      this.$refs.postForm.validate(valid => {
        if (valid) {
          this.loading = true
          if (this.isEdit) {
            editReplyMessage(this.postForm).then(response => {
              // console.log(response)
              this.$notify({
                title: '成功',
                message: '编辑成功',
                type: 'success',
                duration: 2000
              })
              this.loading = false
              this.$router.go(-1)
            }).catch(err => {
              console.log(err)
            })
          } else {
            addReplyMessage(this.postForm).then(response => {
              // console.log(response)
              this.$notify({
                title: '成功',
                message: '添加成功',
                type: 'success',
                duration: 2000
              })
              this.loading = false
              this.$router.go(-1)
            }).catch(err => {
              console.log(err)
            })
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm() {
      this.$refs.postForm.resetFields()
    }
  }
}
</script>

<style lang="scss" scoped>
.create-post-container {
  position: relative;
  .reply-form {
    padding: 40px;
  }
}
</style>
